<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/08/28
 * Time: 23:38
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cha;

use app\admin\controller\BaseController;
use app\common\model\ChannelAttr;
use app\common\service\logistics\ChannelService;

/**
 * 物流属性
 * Class AttrsController
 * @package app\admin\controller\cha
 */
class AttrsController extends BaseController
{
    /**
     * 首页
     * @date 2021/08/29
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $attrs = ChannelAttr::order("attr_id desc");
            $this->searchModel($attrs, [
                'like' => ['code', 'attr_name'],
                'times' => ['create_time'],
            ]);
            $limit = $this->getPageSize();
            $attrs = $attrs->paginate($limit);
            $this->assign('list', $attrs->getCollection());
            $this->assign('page', $attrs->render());
            return $this->fetch('lists');
        }
        return $this->fetch('index');
    }

    /**
     * 添加属性
     * @date 2021/08/29
     * @author longli
     */
    public function add()
    {
        if($id = $this->request->request("attr_id"))
            $this->assign('attr', ChannelAttr::get($id));
        return $this->fetch('add');
    }

    /**
     * 保存属性
     * @date 2021/08/29
     * @author longli
     */
    public function save()
    {
        $tableName = ChannelAttr::getTable();
        $validate = \think\facade\Validate::make([
            'attr_name'  => "require|unique:{$tableName},attr_name",
            'code'  => "require|unique:{$tableName},code",
        ],[
            'attr_name.require' => '属性名称必填',
            'attr_name.unique' => '属性名称不能重复',
            'code.require' => '属性编号必填',
            'code.unique' => '属性编号不能重复',
        ]);
        $data = $this->request->post();
        if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
        ChannelService::getInstance()->addAttr($data)
            ? $this->success("操作成功")
            : $this->error("操作失败");
    }

    /**
     * 删除属性
     * @date 2021/08/29
     * @author longli
     */
    public function delete()
    {
        $ids = $this->request->get("ids");
        if(empty($ids)) $this->error("非法操作");
        ChannelAttr::destroy($ids);
    }

    /**
     * 搜索属性
     * @date 2021/08/29
     * @author longli
     */
    public function get()
    {
        $code = $this->request->request('code', '', 'trim');
        $attr = ChannelAttr::field(['attr_id', 'attr_name', 'code'])->order("attr_id desc");
        if(!empty($code)) $attr->whereRaw("attr_name LIKE ? OR code LIKE ?", ["%$code%", "%$code%"]);
        $this->success('查询成功', "", $attr->paginate(15)->toArray()['data']);
    }
}